<template>
  <el-container>
    <el-header class="elheader">
      <el-row>
        <el-col :span="22" style="display: flex">
          <el-button type="primary" @click="handleAdd" :disabled="!hasAdd">
            添加
          </el-button>
          <!-- <el-button type="primary" @click="handleAdd" :disabled="!hasAdd">
            导出Excel
          </el-button> -->
          <el-dropdown @command="handleCommand">
            <el-button type="primary">
              Excel<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="import">导入</el-dropdown-item>
              <el-dropdown-item command="export">导出</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-form ref="qyeryData" :model="qyeryData" label-width="80px">
            <el-form-item label="用户昵称">
              <el-input
                v-model="qyeryData.name"
                clearable
                @change="query"
              ></el-input>
            </el-form-item>
            <el-form-item label="用户账号">
              <el-input
                v-model="qyeryData.account"
                clearable
                @change="query"
              ></el-input>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="2" class="flexend">
          <el-button type="primary" @click="query">查询</el-button>
        </el-col>
      </el-row>
    </el-header>
    <backline />
    <el-main>
      <pg-el-table-url
        ref="pgTable"
        :qyeryData="qyeryData"
        :tableHeadConfig="tableHeadConfigUrl"
        tableUrl="/api/User/QueryData"
      >
        <template v-slot:operation="slotData">
          <el-button
            type="info"
            :disabled="!hasQuery"
            @click="handleEdit(slotData.elscope.row), false"
          >
            查看
          </el-button>
          <el-button
            type="primary"
            :disabled="!hasUpdate"
            @click="handleEdit(slotData.elscope.row, true)"
          >
            编辑
          </el-button>
          <el-button
            type="danger"
            :disabled="!hasDelete"
            @click="handleDelete(slotData.elscope.$index, slotData.elscope.row)"
          >
            删除
          </el-button>
        </template>
      </pg-el-table-url>
    </el-main>

    <el-dialog
      title="用户信息"
      :visible.sync="dialogFormVisible"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="dialogform" :disabled="!isEdit">
        <el-form-item label="用户昵称">
          <el-input
            v-model="dialogform.name"
            autocomplete="off"
            maxlength="20"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="用户账号">
          <el-input
            v-model="dialogform.account"
            autocomplete="off"
            maxlength="20"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="用户角色">
          <el-select
            style="width: 100%"
            v-model="dialogform.roleIds"
            multiple
            placeholder="请选择"
          >
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div v-if="isAdd" style="color: red">初始密码 666666</div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleDialogFormVisible()"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      title="提示"
      :visible.sync="dialogVisibleImport"
      width="30%"
      :before-close="handleCloseImport"
    >
      <span>这是一段信息</span>

      <div>
        <el-upload
          class="upload-demo"
          action
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :before-remove="beforeRemove"
          multiple
          :limit="1"
          :on-exceed="handleExceed"
          :file-list="fileList"
          :http-request="uploadFile"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">
            只能上传jpg/png文件，且不超过500kb
          </div>
        </el-upload>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleImport = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisibleImportFun"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </el-container>
</template>

<script>
import { AddOrUpdateUser, DeleteUser, UserExport } from "@/api/user";
import { GetExportFile, UploadPostFile } from "@/api/file";
import { GetAllRole } from "@/api/role";
import MyMixin from "@/util/mixin";
export default {
  mixins: [MyMixin],
  data() {
    return {
      // menuUrl: this.$route.path,
      qyeryData: {},
      tableHeadConfigUrl: [
        { field: "id", label: "Id", width: 200 },
        { field: "name", label: "用户名称", width: 200 },
        { field: "account", label: "用户账号", width: 200 },
        { field: "roleDtoListStr", label: "角色管理" },
        {
          fixed: "right",
          columnType: "slot",
          slotName: "operation",
          label: "操作按钮",
          width: 300,
        },
      ],
      formLabelWidth: "120px",
      dialogFormVisible: false,
      dialogform: { name: "", account: "" },
      isEdit: false,
      isAdd: false,
      roleList: [],

      //导入
      dialogVisibleImport: false,
      fileList: [],
    };
  },
  methods: {
    query() {
      this.$refs.pgTable.query();
    },
    async handleAdd() {
      this.dialogFormVisible = true;
      this.dialogform = {};
      this.isEdit = true;
      this.isAdd = true;
      await this.getAllRole();
    },
    async handleEdit(row, isEdit) {
      this.dialogFormVisible = true;
      this.dialogform.id = row.id;
      this.dialogform.name = row.name;
      this.dialogform.account = row.account;
      // this.dialogform.roleIds = row.roleIds; 不渲染
      this.$set(this.dialogform, "roleIds", row.roleIds);
      this.isEdit = isEdit;
      this.isAdd = false;
      await this.getAllRole();
    },
    async getAllRole() {
      var res = await GetAllRole();
      this.roleList = res.data;
    },
    async handleDelete(index, row) {
      console.log(index, row);

      this.$confirm("您确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await DeleteUser({ userId: row.id });
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.query();
        })
        .catch(() => {
          // this.$message({
          //   type: "info",
          //   message: "已取消删除",
          // });
        });

      //
    },
    async handleDialogFormVisible() {
      //添加或者修改用户信息
      if (this.isEdit) {
        await AddOrUpdateUser(this.dialogform);
        this.query();
      }
      this.dialogFormVisible = false;
    },
    async handleCommand(command) {
      let that = this;
      var queryInput = JSON.parse(JSON.stringify(that.qyeryData));
      queryInput.fileName = "用户列表";
      queryInput.pages = 1;
      queryInput.rows = that.$refs.pgTable.total;

      if (command == "export") {
        var exportCapDto = {
          isCap: false,
          // taskPerformanceId: 0,
          queryInput: queryInput,
        };
        var resFile = await UserExport(exportCapDto);

        var res = await GetExportFile({ taskPerformanceId: resFile.data });

        var fileName = decodeURI(
          res.headers["content-disposition"].split("''")[1]
        );
        let url = window.URL.createObjectURL(
          new Blob([res.data], { type: res.headers["content-type"] })
        );
        let link = document.createElement("a");
        link.style.display = "none";
        link.href = url;
        link.setAttribute("download", fileName);
        document.body.appendChild(link);
        link.click();
      } else {
        that.dialogVisibleImport = true;
      }
    },

    async dialogVisibleImportFun() {
      this.dialogVisibleImport = false;
    },
    handleCloseImport(done) {
      debugger;
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },

    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    async uploadFile(fileObj) {
      var a = fileObj;
      debugger;
      // let formData = new FormData();
      // formData.set("file", fileObj.file);

      const formData = new FormData();
      formData.append("file", fileObj.file);

      var aa = await UploadPostFile(formData);
      debugger;
    },
  },
};
</script>

<style>
.el-message-box {
  width: 210px !important;
}
</style>